/**
 *  Copyright 23.07.2012 oliver.keusemann@googlemail.com
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package de.xelerity.geolessi.srv.impl.mixed;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import de.xelerity.geolessi.srv.mixed.WSCallerI;

public class WSCaller1 implements WSCallerI {

	private String PROXYHOST = "";
	private int PROXYPORT = 0; /* 8080 */

	public WSCaller1(String proxy, int proxyport) {
		PROXYHOST = proxy;
		PROXYPORT = proxyport;
	}

	public WSCaller1() {
	}

	public byte[] call(String URL) throws Exception {

		HttpClient client = new HttpClient();

		if (PROXYHOST != null && PROXYHOST.trim().length() > 0) {
			client.getHostConfiguration().setProxy(PROXYHOST, PROXYPORT);
		}

		GetMethod method = new GetMethod(URL);

		try {
			// Execute the method.
			int statusCode = client.executeMethod(method);

			if (statusCode != HttpStatus.SC_OK) {
				throw new Exception("HTTP-Status:" + statusCode + ". Get failed: " + method.getStatusLine());
			}

			byte[] responseBody = method.getResponseBody();
			return (responseBody == null ? new byte[0] : responseBody);

		} catch (Throwable e) {
			if (method != null) {
				method.releaseConnection();
				method = null;
			}
			throw new Exception("Call Failed:" + e.getMessage() + " [" + e.getClass().getSimpleName() + "]");
		} finally {
			if (method != null) {
				method.releaseConnection();
			}
		}
	}

	@Override
	public void addProperty(String Key, String Value) {

		if (Key != null && Key.equalsIgnoreCase("PROXYHOST")) {
			PROXYHOST = (Value == null ? "" : Value.trim());
		}
		if (Key != null && Key.equalsIgnoreCase("PROXYPORT")) {
			PROXYPORT = Integer.parseInt((Value == null ? "8080" : Value.trim()));
		}

	}

}
